package org.umss.fixturebuilder.builder.data;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.umss.fixturebuilder.builder.model.Team;

/**
 *
 * @author Daniela Meneses
 */
public class FileDataSource implements DataSource {

    private final String fileName;

    public FileDataSource(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public List<Team> getTeams() throws DataSourceException {
        List<Team> teams = new ArrayList<Team>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(fileName));
            String teamName = reader.readLine();

            while (teamName != null) {
                teams.add(new Team(teamName));
                teamName = reader.readLine();
            }
        } catch (FileNotFoundException ex) {
            throw new DataSourceException(ErrorCode.FILE_NOT_FOUND_EXCEPTION, "The file was not found.", ex.getCause());
        } catch (IOException ex) {
            throw new DataSourceException(ErrorCode.IO_EXCEPTION, "There was a problem reading the data.", ex.getCause());
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                throw new DataSourceException(ErrorCode.IO_EXCEPTION, "There was a problem reading the data.", ex.getCause());
            }
        }

        return teams;
    }
}
